package edu.ucsc.gameAI.conditions;

import java.util.Vector;

import pacman.game.Constants.DM;
import pacman.game.Constants.GHOST;
import pacman.game.Game;
import edu.ucsc.gameAI.ICondition;
import edu.ucsc.gameAI.PacmanConstants;

public class CheckHowManyPPRemainANDGhostDistance implements ICondition{

	@Override
	public boolean test(Game game) {
		
		int pacManCurrentNode = game.getPacmanCurrentNodeIndex();
		
		Vector<GHOST> edibleGhosts = new Vector<GHOST>();
		Vector<GHOST> nonEdibleGhosts = new Vector<GHOST>();

		
		for (GHOST ghost: GHOST.values()){
			if(game.isGhostEdible(ghost)){ //if any ghosts Are edible
				edibleGhosts.add(ghost); // store which ghosts are edible.	
			}
			else
				nonEdibleGhosts.add(ghost);
		}
		
		int closestEdibleGhostDistance = Integer.MAX_VALUE;
		int closestEdibleGhostIndex = -1;
	
		for (GHOST edibleGhost: edibleGhosts){
			int currentGhostIndex = game.getGhostCurrentNodeIndex(edibleGhost);
			if(closestEdibleGhostDistance > game.getShortestPathDistance(pacManCurrentNode, currentGhostIndex))
			{
				closestEdibleGhostDistance = game.getShortestPathDistance(pacManCurrentNode, currentGhostIndex);
				closestEdibleGhostIndex = game.getGhostCurrentNodeIndex(edibleGhost);
			}
		}
		
		if (closestEdibleGhostIndex != -1)
		{
			int[] pathToCurrentEdibleGhost = game.getShortestPath(pacManCurrentNode, closestEdibleGhostIndex);
			
			for(GHOST dangerGhost : nonEdibleGhosts)
			{
				for(int i=0; i < pathToCurrentEdibleGhost.length; i++){
					if(pathToCurrentEdibleGhost[i] == game.getGhostCurrentNodeIndex(dangerGhost) &&
						game.getShortestPathDistance(pacManCurrentNode, game.getGhostCurrentNodeIndex(dangerGhost)) < 
						PacmanConstants.safeDistance)
					{
						return false;
					}
				}
			}

			switch(game.getActivePowerPillsIndices().length)
			{
			case 4:
				return true;
			case 3: 
				return game.getShortestPathDistance(game.getPacmanCurrentNodeIndex(), closestEdibleGhostIndex) < 
						PacmanConstants.edibleGhostDistance - PacmanConstants.threePPRemainDistanceToCheck;
			case 2: 
				return game.getShortestPathDistance(game.getPacmanCurrentNodeIndex(), closestEdibleGhostIndex) < 
						PacmanConstants.edibleGhostDistance - PacmanConstants.twoPPRemainDistanceToCheck;
			case 1: 
				return game.getShortestPathDistance(game.getPacmanCurrentNodeIndex(), closestEdibleGhostIndex) < 
						PacmanConstants.edibleGhostDistance - PacmanConstants.onePPRemainsDistanceToCheck;
			case 0: 
				return game.getShortestPathDistance(game.getPacmanCurrentNodeIndex(), closestEdibleGhostIndex) < 
						PacmanConstants.edibleGhostDistance - PacmanConstants.noPPRemainDistanceToCheck;
			}
		}
		return false;
	}

}
